package it.polimi.swimv2.session;

import it.polimi.swimv2.entities.Ability;
import it.polimi.swimv2.entities.User;
import it.polimi.swimv2.remote.HelpSearchManagerRemote;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Session Bean implementation class HelpSearchManager
 */
@Stateless
public class HelpSearchManager implements HelpSearchManagerRemote {
	@PersistenceContext(unitName = "swimv2")
	private EntityManager em;
	
	@EJB FriendsManagerLocal friendsManager;
	
	/**
	 * Default constructor.
	 */
	public HelpSearchManager() {

	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<User> searchByAbility(String abilityName, String city) {

		Query q = em.createQuery("SELECT OBJECT(u) "
				+ "FROM User u, IN(u.declaredAbilities) a "
				+ "WHERE a.name = :abilityName " +
				"AND u.city LIKE '"+city+"%'");
		q.setParameter("abilityName", abilityName);
		List<User> result=q.getResultList();
		return result;
	}

	@Override
	public Collection<User> searchFriendByAbility(String username,
			String abilityName, String city) {
		
		Collection<User> result=new LinkedList<User>();
		Ability a= em.find(Ability.class, abilityName);
		User u=em.find(User.class, username);
		if (a ==null||u==null){
			return result;
		}
		Collection<User> userWithAbility=searchByAbility(abilityName, city);
		result = friendsManager.getFriendsOf(username);
		result.retainAll(userWithAbility);
		return result;
	}
}
